# -*- coding: utf-8 -*-
__author__ = 'liubei'

import pymongo
from bson.objectid import ObjectId
import time
import topic as topicDb
import db_engine
import aes
import db_dashboard
import datetime
import pytz
import az_dateutil
import api_statistics

host = db_engine.host


def query(phone):
    print 'do query by userPhone'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    userC = db.user
    return userC.find_one({"userPhone": phone})


def createUser(dic):
    print 'do createUser'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    userC = db.user
    userC.insert(dic)


def updateUserPwd(dic):
    print 'do updateUser'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    userC = db.user
    userC.update({"userPhone": dic['userPhone']}, {'$set': {'userPwd': dic['userPwd']}})


def createToken(dic):
    print 'do createToken'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    tokenC = db.token
    tokenC.insert(dic)


def queryUserByToken(token):
    print 'do queryUserByToken'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    tokenC = db.token
    return tokenC.find_one({'accessToken': token})


def updateBp(dic):
    print 'do createBp'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    bpC = db.bp
    bps = bpC.find({'userPhone': dic['userPhone']}).sort('createDate', -1).limit(1)
    if bps.count() == 0:
        print 'not find bp'
        return bpC.insert(dic)
    for bp in bps:
        cTimeLong = bp['createDate']
        cTime = time.strftime('%Y-%m-%d', time.localtime(cTimeLong))
        now = int(time.time())
        nTime = time.strftime('%Y-%m-%d', time.localtime(now))
        if cTime == nTime:
            print 'update today bp'
            print bpC.update({"_id": bp['_id']}, {'$set': {'bpHighIndex': dic['bpHighIndex'], 'bpLowIndex': dic['bpLowIndex'], 'createDate': now, 'userPhone': dic['userPhone']}})
            return str(bp['_id'])
    print 'not find today bmi'
    return bpC.insert(dic)


def queryBpList(phone, page=0, pageSize=10):
    print 'do queryBpList'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    bpC = db.bp
    if page < 0:
        bps = bpC.find({'userPhone': phone}).sort('createDate', -1)
    else:
        pos = page * pageSize
        bps = bpC.find({'userPhone': phone}).sort('createDate', -1).limit(pageSize).skip(pos)
    bpList = []
    bpDic = {}
    aes_cipher = aes.AESCipher(aes.aes_key)
    for bp in bps:
        bp.pop('userPhone')
        bp['uid'] = str(bp['_id'])
        bp.pop('_id')
        bp['bpLowIndex'] = aes_cipher.decrypt(bp['bpLowIndex'])
        bp['bpHighIndex'] = aes_cipher.decrypt(bp['bpHighIndex'])
        bpList.append(bp)
    bpDic['bps'] = bpList
    bpDic['page'] = page
    bpDic['total'] = bpC.find({'userPhone': phone}).count()
    return bpDic


def deleteBp(bpId):
    print 'do deleteBp'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    bpC = db.bp
    print bpC.remove({'_id': ObjectId(bpId)})


def deleteAllBpByPhone(userPhone):
    print 'do deleteBp'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    bpC = db.bp
    print bpC.remove({'userPhone': userPhone})


def updateBmi(dic):
    print 'do createBmi'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    bmiC = db.bmi
    bmis = bmiC.find({'userPhone': dic['userPhone']}).sort('createDate', -1).limit(1)
    if bmis.count() == 0:
        print 'not find bmi'
        return bmiC.insert(dic)
    for bmi in bmis:
        cTimeLong = bmi['createDate']
        cTime = time.strftime('%Y-%m-%d', time.localtime(cTimeLong))
        now = int(time.time())
        nTime = time.strftime('%Y-%m-%d', time.localtime(now))
        if cTime == nTime:
            print 'update today bmi'
            dic['bmiIndex'] = round(float(dic['weight'])/(float(dic['height'])/100 * float(dic['height'])/100), 2)
            dic['targetBmiIndex'] = round(dic['targetWeight']/(float(dic['height'])/100 * float(dic['height'])/100), 2)
            print bmiC.update({"_id": bmi['_id']}, {'$set': {'height': dic['height'], 'weight': dic['weight'], 'targetWeight': dic['targetWeight'], 'createDate': now, 'bmiIndex': dic['bmiIndex'], 'targetBmiIndex': dic['targetBmiIndex'], 'userPhone': dic['userPhone']}})
            return str(bmi['_id'])
    print 'not find today bmi'
    return bmiC.insert(dic)


def queryBmiList(phone, page=0, pageSize=10):
    print 'do queryBmiList'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    bmiC = db.bmi
    if page < 0:
        bmis = bmiC.find({'userPhone': phone}).sort('createDate', -1)
    else:
        pos = page * pageSize
        bmis = bmiC.find({'userPhone': phone}).sort('createDate', -1).limit(pageSize).skip(pos)
    bmiList = []
    bmiDic = {}
    for bmi in bmis:
        bmi.pop('userPhone')
        bmi['uid'] = str(bmi['_id'])
        bmi.pop('_id')
        bmiList.append(bmi)
    bmiDic['bmis'] = bmiList
    bmiDic['page'] = page
    bmiDic['total'] = bmiC.find({'userPhone': phone}).count()
    return bmiDic


def deleteBmi(bmiId):
    print 'do deleteBp'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    bmiC = db.bmi
    print bmiC.remove({'_id': ObjectId(bmiId)})


def deleteAllBmiByPhone(userPhone):
    print 'do deleteBp'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    bmiC = db.bmi
    print bmiC.remove({'userPhone': userPhone})


#多线程
def updateCholesterol_fix(dic):
    print 'do updateCholesterol'
    tz = pytz.timezone(pytz.country_timezones('cn')[0])
    db_engine.connect('az', host=db_engine.host)
    cTime = datetime.datetime.fromtimestamp(dic['createDate'], tz).strftime("%Y-%m-%d")
    thisDate = datetime.datetime.fromtimestamp(dic['createDate'], tz)
    thisTime = int(az_dateutil.date2timestamp(thisDate.replace(thisDate.year, thisDate.month, thisDate.day, 0, 0, 0)))
    cholesterol = db_dashboard.Cholesterol.objects(userPhone=dic['userPhone'],
                                                   createDate__gte=thisTime-8*60*60,
                                                   createDate__lt=thisTime+16*60*60).first()
    if cholesterol == None:
        cholesterol = db_dashboard.Cholesterol(low=dic['low'], high=dic['high'],
                       tg=dic['tg'], createDate=dic['createDate'],
                       userPhone=dic['userPhone'], tc=dic['tc'], createDateString=cTime).save()
    else:
        cholesterol.update(set__low=dic['low'], set__high=dic['high'],
                       set__tg=dic['tg'], set__createDate=dic['createDate'],
                       set__userPhone=dic['userPhone'], set__tc=dic['tc'], set__createDateString=cTime)
    return str(cholesterol.id)


def updateCholesterol(dic):
    print 'do updateCholesterol'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    cholesterolC = db.cholesterol
    cholesterols = cholesterolC.find({'userPhone': dic['userPhone']}).sort('createDate', -1).limit(1)
    if cholesterols.count() == 0:
        print 'not find cholesterol'
        return cholesterolC.insert(dic)
    for cholesterol in cholesterols:
        cTimeLong = cholesterol['createDate']
        cTime = time.strftime('%Y-%m-%d', time.localtime(cTimeLong))
        now = int(dic['createDate'])
        nTime = time.strftime('%Y-%m-%d', time.localtime(now))
        if cTime == nTime:
            print 'update today cholesterol'
            print cholesterolC.update({"_id": cholesterol['_id']}, {'$set': {'low': dic['low'], 'high': dic['high'], 'tg': dic['tg'], 'createDate': now, 'userPhone': dic['userPhone'], 'tc': dic['tc']}})
            return str(cholesterol['_id'])
    print 'not find today cholesterol'
    return cholesterolC.insert(dic)


def queryCholesterolList(phone, page=0, pageSize=10):
    print 'do queryCholesterolList'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    cholesterolC = db.cholesterol
    if page < 0:
        cholesterols = cholesterolC.find({'userPhone': phone}).sort('createDate', -1)
    else:
        pos = page * pageSize
        cholesterols = cholesterolC.find({'userPhone': phone}).sort('createDate', -1).limit(pageSize).skip(pos)
    cholesterolList = []
    cholesterolDic = {}
    aes_cipher = aes.AESCipher(aes.aes_key)
    for cholesterol in cholesterols:
        cholesterol.pop('userPhone')
        cholesterol['uid'] = str(cholesterol['_id'])
        cholesterol.pop('_id')
        if cholesterol.has_key('createDateString'):
            cholesterol.pop('createDateString')
        cholesterol['high'] = aes_cipher.decrypt(cholesterol['high'])
        cholesterol['low'] = aes_cipher.decrypt(cholesterol['low'])
        cholesterol['tg'] = aes_cipher.decrypt(cholesterol['tg'])
        cholesterol['tc'] = aes_cipher.decrypt(cholesterol['tc'])
        cholesterolList.append(cholesterol)
    cholesterolDic['cholesterols'] = cholesterolList
    cholesterolDic['page'] = page
    cholesterolDic['total'] = cholesterolC.find({'userPhone': phone}).count()
    return cholesterolDic


def deleteCholesterol(bmiId):
    print 'do deleteBp'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    cholesterolC = db.cholesterol
    print cholesterolC.remove({'_id': ObjectId(bmiId)})


def deleteAllCholesterolByPhone(userPhone):
    print 'do deleteBp'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    cholesterolC = db.cholesterol
    print cholesterolC.remove({'userPhone': userPhone})


def queryTopicList(userPhone=None, page=0, pageSize=10):
    print 'do queryTopicList'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    topicC = db.topic
    if page < 0:
        topics = topicC.find()
    else:
        pos = page * pageSize
        topics = topicC.find().limit(pageSize).skip(pos)
    topicList = []
    topicDic = {}
    user = db_engine.queryUser(userPhone)
    for topicModel in topics:
        #smoke knowledge
        if topicModel['index'] == '16':
            if user.isSmoke == 1:
                topicModel['uid'] = str(topicModel['_id'])
                topicModel.pop('_id')
                if userPhone == None:
                    topicModel['isRead'] = 0
                else:
                    topicModel['isRead'] = topicDb.isReadByTopicId(userPhone, topicModel['uid'])
                topicList.append(topicModel)
            continue

        topicModel['uid'] = str(topicModel['_id'])
        topicModel.pop('_id')
        if userPhone == None:
            topicModel['isRead'] = 0
        else:
            topicModel['isRead'] = topicDb.isReadByTopicId(userPhone, topicModel['uid'])
        topicList.append(topicModel)

    topicDic['topics'] = topicList
    topicDic['page'] = page
    topicDic['total'] = topicC.find().count()
    return topicDic


def queryUnReadArticleCount(userPhone=None):
    print 'do queryUnReadArticleCount'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    topicC = db.topic
    articleC = db.article
    topics = topicC.find()
    count = 0
    user = db_engine.queryUser(userPhone)
    now = int(time.time())
    timeDelat = (now - user.createDate)/(24*60*60)+1
    for topicModel in topics:
        if topicModel['index'] == '16' and user.isSmoke == 0:
            continue
        articles = articleC.find({"topicId": str(topicModel['_id'])})

        for article in articles:
            if not article.has_key('articleIndex'):
                articleIndex = topicModel['sentIndex']
            else:
                articleIndex = int(article['articleIndex'])
            for msgStrategy in topicDb.queryLongMsgStrategy(timeDelat, user.isSmoke):
                if msgStrategy.msg_no == articleIndex:
                    article['isRead'] = topicDb.isReadByArticleId(userPhone, str(article['_id']))
                    if article['isRead'] == 0:
                        count += 1
    return count


def queryArticleListByTopicId(uid, userPhone=None):
    print 'do queryArticleListByTopicId'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    articleC = db.article
    articles = articleC.find({"topicId": uid})
    articleList = []
    topicDic = {}
    user = db_engine.queryUser(userPhone)
    now = int(time.time())
    timeDelat = (now - user.createDate)/(24*60*60)+1

    topicC = db.topic
    topicModel = topicC.find_one({'_id': ObjectId(uid)})
    for article in articles:
        if not article.has_key('articleIndex'):
            articleIndex = topicModel['sentIndex']
        else:
            articleIndex = int(article['articleIndex'])
        for msgStrategy in topicDb.queryLongMsgStrategy(timeDelat, user.isSmoke):
            if msgStrategy.msg_no == articleIndex:
                article['uid'] = str(article['_id'])
                article.pop('_id')
                article.pop('topicId')
                article.pop('content')
                if userPhone == None:
                    article['isRead'] = 0
                else:
                    article['isRead'] = topicDb.isReadByArticleId(userPhone, article['uid'])
                articleList.append(article)

    topicDic['articles'] = articleList
    topicDic['title'] = topicModel['title']
    topicDic['des'] = topicModel['des']
    topicDic['image'] = topicModel['image']
    topicDic['uid'] = uid
    return topicDic


def queryArticle(uid, userPhone=None):
    print 'do queryArticle'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    articleC = db.article
    article = articleC.find_one({'_id': ObjectId(uid)})
    article['uid'] = str(article['_id'])
    article.pop('_id')
    article.pop('topicId')
    if userPhone:
        topicDb.updateReadByArticleId(userPhone, uid)
    # save log
    api_statistics.logLongMessage(userPhone, article['articleIndex'])
    return article


def querySmokeList(phone, page=0, pageSize=10):
    print 'do querySmokeList'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    smokeC = db.smoke
    if page < 0:
        smokes = smokeC.find({'userPhone': phone}).sort('createDate', -1)
    else:
        pos = page * pageSize
        smokes = smokeC.find({'userPhone': phone}).sort('createDate', -1).limit(pageSize).skip(pos)
    smokeList = []
    smokeDic = {}
    for smoke in smokes:
        smoke.pop('userPhone')
        smoke['uid'] = str(smoke['_id'])
        smoke.pop('_id')
        smokeList.append(smoke)
    smokeDic['smokes'] = smokeList
    smokeDic['page'] = page
    smokeDic['total'] = smokeC.find({'userPhone': phone}).count()
    return smokeDic


def updateSmoke(dic):
    print 'do createSmoke'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    smokeC = db.smoke
    smokes = smokeC.find({'userPhone': dic['userPhone']})
    if smokes.count() == 0:
        print 'not find smoke'
        return smokeC.insert(dic)
    for smoke in smokes:
        cTimeLong = smoke['createDate']
        cTime = time.strftime('%Y-%m-%d', time.localtime(cTimeLong))
        nTime = time.strftime('%Y-%m-%d', time.localtime(int(dic['createDate'])))
        if cTime == nTime:
            print 'update today smoke'
            print smokeC.update({"_id": smoke['_id']}, {'$set': {'createDate': smoke['createDate'], 'count': dic['count'], 'userPhone': dic['userPhone']}})
            return str(smoke['_id'])
    print 'not find today smoke'
    return smokeC.insert(dic)


def queryExerciseloglist(phone, page=0, pageSize=10):
    print 'do queryExerciseloglist'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    exericelogC = db.exericelog
    exericeC = db.exerice
    if page < 0:
        exericelogs = exericelogC.find({'userPhone': phone}).sort('createDate', -1)
    else:
        pos = page * pageSize
        exericelogs = exericelogC.find({'userPhone': phone}).sort('createDate', -1).limit(pageSize).skip(pos)
    exericelogList = []
    exericelogDic = {}
    for exericelog in exericelogs:
        exericelog.pop('userPhone')
        exericelog['uid'] = str(exericelog['_id'])
        exericelog.pop('_id')

        exerices = exericeC.find({'exericeId': exericelog['uid']})
        exericeList = []
        for exerice in exerices:
            exerice['uid'] = str(exerice['_id'])
            exerice.pop('_id')
            exerice.pop('exericeId')
            exericeList.append(exerice)

        exericelog['exerices'] = exericeList
        exericelogList.append(exericelog)

    i = 0
    for exericelog in exericelogList:
        setNextTargetTotalMinute(i, exericelog, exericelogList)
        i += 1

    exericelogDic['exericelogs'] = exericelogList
    exericelogDic['page'] = page
    exericelogDic['total'] = exericelogC.find({'userPhone': phone}).count()
    return exericelogDic


def setNextTargetTotalMinute(index, exericelog, exericelogList):
    if exericelog.has_key('targetTotalMinute') and int(exericelog['targetTotalMinute']) == 0 and index+1 < len(exericelogList):
        nextExericeLog = exericelogList[index+1]
        if nextExericeLog.has_key('targetTotalMinute'):
            exericelog['targetTotalMinute'] = nextExericeLog['targetTotalMinute']
            setNextTargetTotalMinute(index + 1, exericelog, exericelogList)
    else:
        return


def updateExerciseloglist(dic):
    print 'do updateExerciseloglist'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    exericelogC = db.exericelog
    exericelogs = exericelogC.find({'userPhone': dic['userPhone']})
    #
    exericeC = db.exerice

    if exericelogs.count() == 0:
        print 'not find Exerciselog'
        dic['calorieTotalCount'] = 0
        dic['totalMinute'] = 0
        return exericelogC.insert(dic)
    for exericelog in exericelogs:
        exerices = exericeC.find({'exericeId': str(exericelog['_id'])})
        total = 0
        totalMin = 0
        for exerice in exerices:
            total = total + exerice['calorieCount']
            totalMin += exerice['min']

        cTimeLong = exericelog['createDate']

        tz = pytz.timezone(pytz.country_timezones('cn')[0])
        cTime = datetime.datetime.fromtimestamp(float(cTimeLong), tz).strftime("%Y-%m-%d")
        nTime = datetime.datetime.fromtimestamp(int(dic['createDate']), tz).strftime("%Y-%m-%d")
        if cTime == nTime:
            print 'update today Exerciselog'
            if not dic.has_key('targetCalorieTotalCount'):
                dic['targetCalorieTotalCount'] = 0
            if not dic.has_key('targetTotalMinute'):
                dic['targetTotalMinute'] = exericelog['targetTotalMinute']
            print exericelogC.update({"_id": exericelog['_id']}, {'$set': {'createDate': exericelog['createDate'], 'targetCalorieTotalCount': dic['targetCalorieTotalCount'], 'userPhone': dic['userPhone'], 'calorieTotalCount': total, 'totalMinute': totalMin, 'targetTotalMinute': dic['targetTotalMinute']}})
            return str(exericelog['_id'])
    print 'not find today Exerciselog'
    dic['calorieTotalCount'] = 0
    dic['totalMinute'] = 0
    return exericelogC.insert(dic)


def deleteExerice(eid):
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    exericelogC = db.exericelog
    exericeC = db.exerice
    exerice = exericeC.find_one({'_id': ObjectId(eid)})
    exericelog = exericelogC.find_one({'_id': ObjectId(exerice['exericeId'])})
    exericelog['totalMinute'] = exericelog['totalMinute'] - exerice['min']
    print exericelogC.update({"_id": exericelog['_id']}, {'$set': {'totalMinute': exericelog['totalMinute']}})
    print exericeC.remove({'_id': ObjectId(eid)})


def findExerciseloglist(eid):
    print 'do findExerciseloglist'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    exericelogC = db.exericelog
    exericeC = db.exerice
    exericelog = exericelogC.find_one({'_id': ObjectId(eid)})
    exericelog['uid'] = eid
    exericelog.pop('_id')
    exericelog.pop('userPhone')
    exerices = exericeC.find({'exericeId': exericelog['uid']})

    exericeList = []
    for exerice in exerices:
        exerice['uid'] = str(exerice['_id'])
        exerice.pop('_id')
        exerice.pop('exericeId')
        exericeList.append(exerice)

    exericelog['exerices'] = exericeList
    return exericelog


def querySportEventList():
    print 'do querySportEventList'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    sporteventC = db.sportevent
    sportevents = sporteventC.find()
    exericeList = []
    for sportevent in sportevents:
        sportevent['uid'] = str(sportevent['_id'])
        type(sportevent)
        sportevent.pop('_id')
        exericeList.append(sportevent)
    return exericeList


def querySportEventByType(typeId):
    print 'do querySportEventList'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    sporteventC = db.sportevent
    sportevent = sporteventC.find_one({'type': typeId})
    return sportevent


def updateExerciseloglistByExerice(dic):
    print 'do updateExerciseloglist'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    #
    exericeC = db.exerice
    exericelogC = db.exericelog
    #find exericelog
    exericelogs = exericelogC.find({'userPhone': dic['userPhone']})
    find_exerelog = False
    tz = pytz.timezone(pytz.country_timezones('cn')[0])
    for exericelog in exericelogs:
        cTimeLong = exericelog['createDate']
        cTime = datetime.datetime.fromtimestamp(float(cTimeLong), tz).strftime("%Y-%m-%d")
        nTime = datetime.datetime.fromtimestamp(int(dic['createDate']), tz).strftime("%Y-%m-%d")
        #find
        if cTime == nTime:
            dic['uid'] = str(exericelog['_id'])
            find_exerelog = True
            break
    #not find
    if not find_exerelog:
        insertDic = {}
        insertDic['createDate'] = dic['createDate']
        insertDic['userPhone'] = dic['userPhone']
        insertDic['targetCalorieTotalCount'] = 0
        insertDic['calorieTotalCount'] = 0
        insertDic['totalMinute'] = 0
        insertDic['targetTotalMinute'] = 150
        dic['uid'] = str(exericelogC.insert(insertDic))

    exerices = exericeC.find({'exericeId': dic['uid']})
    sportEvent = querySportEventByType(dic['type'])
    total = int(sportEvent['unit']) * dic['weight'] * dic['min']

    for exerice in exerices:
        #todo: total == 0 remove?
        if exerice['type'] == dic['type']:
            print exericeC.update({"_id": exerice['_id']}, {'$set': {'calorieCount': total, 'exericeId': exerice['exericeId'], 'min': dic['min'], 'type': dic['type'], 'typeName': sportEvent['typeName']}})
            #refresh count
            total = 0
            totalMin = 0
            exerices = exericeC.find({'exericeId': dic['uid']})
            for exerice in exerices:
                total = total + exerice['calorieCount']
                totalMin += exerice['min']
            exericelog = exericelogC.find_one({"_id": ObjectId(exerice['exericeId'])})
            if not exericelog.has_key('targetCalorieTotalCount'):
                exericelog['targetCalorieTotalCount'] = 0
            print exericelogC.update({"_id": ObjectId(exerice['exericeId'])}, {'$set': {'createDate': exericelog['createDate'], 'targetCalorieTotalCount': exericelog['targetCalorieTotalCount'], 'userPhone': exericelog['userPhone'], 'calorieTotalCount': total, 'totalMinute': totalMin, 'targetTotalMinute': exericelog['targetTotalMinute']}})
            return str(exerice['exericeId'])

    #not exist
    toInsertdic = {}
    toInsertdic['calorieCount'] = total
    toInsertdic['exericeId'] = dic['uid']
    toInsertdic['min'] = dic['min']
    toInsertdic['type'] = dic['type']
    toInsertdic['typeName'] = sportEvent['typeName']

    uid = str(exericeC.insert(toInsertdic))
    uid = exericeC.find_one({'_id': ObjectId(uid)})['exericeId']
    #refresh count
    total = 0
    totalMin = 0
    exerices = exericeC.find({'exericeId': dic['uid']})
    for exerice in exerices:
        total = total + exerice['calorieCount']
        totalMin += exerice['min']
    exericelog = exericelogC.find_one({"_id": ObjectId(uid)})
    print exericelogC.update({"_id": ObjectId(uid)}, {'$set': {'createDate': exericelog['createDate'], 'userPhone': exericelog['userPhone'], 'calorieTotalCount': total, 'totalMinute': totalMin, 'targetTotalMinute': exericelog['targetTotalMinute']}})
    return uid


def queryQuestionListByTopicId(uid, userPhone):
    print 'do queryQuestionListByTopicId'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    questionC = db.question
    questionList = []
    questionDic = {}
    print uid
    if uid == '0':
        questions = questionC.find()
        questionDic['title'] = 'all'
    else:
        questions = questionC.find({"topicId": uid})
        topicC = db.topic
        topic = topicC.find_one({'_id': ObjectId(uid)})
        if topic == None:
            return questionDic
        questionDic['title'] = topic['title']
    questionDic['uid'] = uid
    user = db_engine.queryUser(userPhone)
    now = int(time.time())
    timeDelat = (now - user.createDate)/(24*60*60)+1
    for question in questions:
        articleIndex = int(question['articleIndex'])
        for strategy in topicDb.queryQuestionStrategy(timeDelat, user.isSmoke):
            if articleIndex in strategy.quiz_nos:
                question['uid'] = str(question['_id'])
                question.pop('_id')
                question.pop('topicId')
                question.pop('correctAnswer')
                questionList.append(question)
    questionDic['questions'] = questionList

    return questionDic


def updateUserAnswerRecord(dic):
    print 'do updateUserAnswerRecord'
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    questionC = db.question
    questionRecordC = db.questionRecord
    if dic['uid'] == '0':
        questions = questionC.find()
    else:
        questions = questionC.find({"topicId": dic['uid']})
    user = db_engine.queryUser(dic['userPhone'])
    now = int(time.time())
    timeDelat = (now - user.createDate)/(24*60*60)+1
    answerList = []
    recordDic = {}
    correctCount = 0
    answers = dic['answers']
    count = 0
    for question in questions:
        articleIndex = int(question['articleIndex'])
        for strategy in topicDb.queryQuestionStrategy(timeDelat, user.isSmoke):
            if articleIndex in strategy.quiz_nos:
                count += 1

        question['uid'] = str(question['_id'])
        for answer in answers:
            if question['uid'] == answer['uid']:
                answer['title'] = question['title']
                answer['type'] = question['type']
                answer['correctAnswer'] = question['correctAnswer']
                if question['correctAnswer'] == answer['userAnswer']:
                    correctCount += 1
                    answer['result'] = 1
                else:
                    answer['result'] = 0
                answerList.append(answer)
                break

    recordDic['score'] = (int)(1.0 * correctCount/count * 100)
    recordDic['answers'] = answerList
    recordDic['userPhone'] = dic['userPhone']
    recordDic['createDate'] = int(time.time())
    #save
    questionRecordC.insert(recordDic)

    #query last three
    dbResponseRecordDic = {}
    dbResponseRecordList = []
    dbRecords = questionRecordC.find({'userPhone': dic['userPhone']}).sort('createDate', -1).limit(3)
    for dbRecordDic in dbRecords:
        dbRecordDic['uid'] = str(dbRecordDic['_id'])
        dbRecordDic.pop('_id')
        dbRecordDic.pop('userPhone')
        dbRecordDic.pop('answers')
        dbResponseRecordList.append(dbRecordDic)
    dbResponseRecordDic['records'] = dbResponseRecordList
    return dbResponseRecordDic


def queryQuestionRecord(uid):
    conn = pymongo.mongo_client.MongoClient(host, port=27017)
    db = conn.az
    questionRecordC = db.questionRecord
    dbRecordDic = questionRecordC.find_one({"_id": ObjectId(uid)})
    dbRecordDic['uid'] = str(dbRecordDic['_id'])
    dbRecordDic.pop('_id')
    dbRecordDic.pop('userPhone')
    return dbRecordDic


if __name__ == "__main__":
    # query('18001822249')
    now = int(time.time())
    timeDelat = (now - 1424901000)/(7*24*60*60)
    print timeDelat